#!/usr/bin/env python3

import json
import os
import re
import base64
import sys
from gitcode_api.pull_request import *
from gitcode_api.repositories import *

debug = False
if debug == False:
    # 取环境变量
    WEBHOOK_PAYLOAD = os.getenv('WEBHOOK_PAYLOAD')
    print("WEBHOOK_PAYLOAD:{}".format(WEBHOOK_PAYLOAD))
    webhook = json.loads(WEBHOOK_PAYLOAD)
    repo = webhook['project']['name']
    owner = webhook['project']['namespace']
    print("repo:{}, owner:{}".format(repo, owner))

    number = os.getenv('MERGE_ID')
    print("number:{}".format(number))
    
    access_token = os.getenv('GITCODE_TOKEN')
    if access_token == None:
        sys.stderr('未定义GITCODE_TOKEN')
        sys.exit(1)
else:
    repo = "homebrew-core-test"
    owner = "Harmonybrew"
    number = 1
    access_token = "sQELcL1yHh6Y7DZPD6LxhUXk"

# 运行测试
build_failure = False
print("run test---")
if  build_failure == True:
    create_pr_label(owner, repo, number, access_token, "ci failure")
    sys.exit(1)

# 测试通过的 new formula PR 添加 Label
if webhook["event_type"] == "merge_request":
    if "(new formula)" in webhook["object_attributes"]["title"]:
        if "new formula" not in webhook["labels"]:
            create_pr_label(owner, repo, number, access_token, "new formula")
            sys.exit(0)


# 审核人员 approved pr 后

if "new formula" in webhook["labels"] and webhook["event_type"] == "merge_request" and "approved_count" in webhook and webhook["approved_count"] >= 1:
    # 机器人添加评论,
    data = {
        "body": """🤖 An automated task has requested bottles to be published to this PR.

    Caution
    
    Please do not push to this PR branch before the bottle commits have been pushed, as this results in a state that is difficult to recover from. If you need to resolve a merge conflict, please use a merge commit. Do not force-push to this PR branch.""",
        "path": "",
        "position": 0,
        "need_to_resolve": False
        }
    create_pr_comment(owner, repo, number, access_token, data)
    # 机器人添加 bottle 信息
    print("编译 bottle")
    file_list_str = get_pr_file_list(owner, repo, number, access_token)
    print("file_list_str type:",type(file_list_str))
    file_list = json.loads(file_list_str)
    print("file_list type:", type(file_list))
    formula_file_path = ""
    for file in file_list:
        patch = file["patch"]
        match = re.match(r"^Formula/[^/]+/[^/]+\.rb$", patch["new_path"])
        if match and file["patch"]["new_file"] == True:
            formula_file_path = file["patch"]["new_path"]
            print("formula_file_path:", formula_file_path)

    file_data_str = get_file_content(owner, repo, formula_file_path, access_token, webhook["object_attributes"]["source_branch"])
    print("file_data_str type:",type(file_data_str))
    file_data  = json.loads(file_data_str)
    encoded_str = file_data["content"]  # 文件内容的 Base64 编码
    decoded_bytes = base64.b64decode(encoded_str)
    formula_content = decoded_bytes.decode('utf-8')  # 转换为字符串
    insert_pos = find_bottle_insert_position(formula_content)
    print("insert_pos:", insert_pos)
    content = '''  bottle do
        sha256 cellar: :any,                 arm64_sequoia: "c0fa5a90d67cb682bb86aeda90bcc9eeb401ea5b23c29e4deb1a96f711054a2c"
        sha256 cellar: :any,                 arm64_sonoma:  "415eeac806a17163df776577ccccf9d1b563e6fea14b3c1e8ba2fdce080fe723"
        sha256 cellar: :any,                 arm64_ventura: "74be363ec979cb61a8fff6df7748b7fbf1a65bc8b2cdade9a5d590358c0dd941"
        sha256 cellar: :any,                 sonoma:        "ca749b0b25ed835cd689ccf863088d94de4ff137237b47d28dc635f94c517cae"
        sha256 cellar: :any,                 ventura:       "ab8621f0fcd75d386e0b127472c35b2043819c4de818abcc9309ba42ad635fdf"
        sha256 cellar: :any_skip_relocation, x86_64_linux:  "8db376229cfb85fb924828e9e582369ea53cf7439b510d7befd53daab15c1403"
    end
    '''
    new_content = modify_file(formula_content, insert_pos - 1, content)
    data = {
        "content": new_content,
        "sha": file_data["sha"],
        "branch": webhook["object_attributes"]["source_branch"],
        "message": "add bottle",
        "author_name": "BrewTestBot",
        "author_email": "BrewTestBot@mail.com"
        }
    update_file(owner, repo, formula_file_path, access_token, data)
    create_pr_label(owner, repo, number, access_token, "CI-published-bottle-commits")
    sys.exit(0)

# 机器人 approved pr
review_pr(owner, repo, number, access_token, True)
if "approved_count" in webhook and webhook["approved_count"] >= 1:
    create_pr_label(owner, repo, number, access_token, "auto merge")
    print("push to merge queue")

